Vue Generate Random Quote:“Vue Generate Random Quote” likely refers to a small web application built using the Vue.js framework that generates random quotes. The application would use Vue.js to create a template that displays a random quote from a pre-defined set of quotes each time the user interacts with the application. This could be accomplished using Vue.js’s built-in data binding and event handling features. The application might also include a button or other interface element that the user can click to generate a new quote.
How can I generate a random quote using Vue js
This code creates a Vue app with a button that generates a random quote when clicked. The app contains an array of quote objects, each with a text and author property.
The data
function returns an object with two properties: quotes
and quote
. quotes
is an array of quote objects and quote
is an empty string that will later hold the generated quote.
The methods
object contains a generateQuote
method, which generates a random quote by selecting a random index from the quotes
array using Math.random()
and setting the quote
property to a formatted string with the text and author of the selected quote.
The mounted
hook calls the generateQuote
method when the app is mounted to initially display a random quote.
When the Generate Quote
button is clicked, the generateQuote
method is called and a new random quote is displayed
Vue Generate Random Quote Example
<div id="app">
<p>{{ quote }}</p>
<button @click="generateQuote">Generate Quote</button>
</div>
<script type="module">
const app = Vue.createApp({
data() {
return {
quotes: [
{
text: "The only way to do great work is to love what you do.",
author: "Steve Jobs"
},
{
text: "You miss 100% of the shots you don't take.",
author: "Wayne Gretzky"
},
{
text: "I have not failed. I've just found 10,000 ways that won't work.",
author: "Thomas Edison"
},
{
text: "Success is not final, failure is not fatal: It is the courage to continue that counts.",
author: "Winston S. Churchill"
},
{
text: "Believe you can and you're halfway there.",
author: "Theodore Roosevelt"
}
],
quote: ""
}
},
methods: {
generateQuote() {
const randomIndex = Math.floor(Math.random() * this.quotes.length);
const randomQuote = this.quotes[randomIndex];
this.quote = `"${randomQuote.text}" - ${randomQuote.author}`;
}
},
mounted() {
this.generateQuote();
}
})
app.mount('#app')
</script>